<template>
  <div id="shop-cart">
    <nav-bar>
      <template v-slot:left></template>
      <template v-slot:default>购物车(<span style="color: red">{{ $store.state.cartCount }}</span>)</template>
      <template v-slot:right></template>
    </nav-bar>

    <div style="margin-top:50px"></div>

    <van-checkbox-group v-model="result" @change="groupChange">
      <van-swipe-cell v-for="(item, index) in list" :key="index">
        <div class="cart-item">
          <div class="left">
            <van-checkbox :name="item.id"></van-checkbox>
            <img v-lazy="item.goods.cover_url" alt="">
            <div class="desc">
              <div class="title">{{item.goods.title}}</div>
              <div class="price"><small>￥</small>{{item.goods.price}}.00</div>
            </div>
          </div>
          <div class="right">
            <div class="num">x{{item.goods.stock}}</div>
            <div class="step">
              <van-stepper v-model="item.num" min="1" :max="item.goods.stock" :name="item.id" async-change @change="onChange" />
            </div>
          </div>
        </div>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="deleteGood(item.id)" />
        </template>
      </van-swipe-cell>
    </van-checkbox-group>

    <van-empty description="购物车空空如也" :image="emptyCart" v-if="!list.length">
      <van-button round type="success" class="bottom-button" @click="$router.push({name: 'Category'})">前往选购</van-button>
    </van-empty>

    <van-submit-bar :price="price * 100" button-text="结算" class="submit-bar" @submit="onSubmit">
      <van-checkbox v-model="checked" @click="checkedAll">全选</van-checkbox>
    </van-submit-bar>

    <div style="margin-bottom: 100px;"></div>
  </div>
</template>

<script>
import {reactive, toRefs, computed, onMounted} from "vue";
import {useRouter} from "vue-router";
import {useStore} from "vuex";
import {Toast} from "vant";
import NavBar from "components/common/navbar/NavBar";

import {getCart, modifyCart, deleteCartItem, checkedCard} from "network/cart";

export default {
  name: "ShopCart",
  components: {
    NavBar,
  },
  setup() {
    // 数据模型
    const state = reactive({
      list: [],
      result: [],
      checked: true,
    })
    // 全选反选
    const checkedAll = () => state.result = state.checked ? state.list.map(item => item.id) : []
    // 选中状态
    const groupChange = () => {
      state.checked = state.list.length === state.result.length
      checkedCard({cart_ids: state.result})
    }
    // 改变数量
    const onChange = (value, detail) => {
      Toast.loading({ forbidClick: true });
      modifyCart(detail.name, {num: value}).then(() => Toast.clear())
    }
    // 删除商品
    const store = useStore()
    const deleteGood = id => deleteCartItem(id).then(res => {
      state.list.splice(state.list.findIndex(item => item.id === id) , 1)
      state.result.splice(state.result.findIndex(item => item === id), 1)
      store.commit('addCart', {count: store.state.cartCount - 1})
    })
    // 计算价格
    const price = computed(() => state.list.filter(item => state.result.includes(item.id)).reduce((prev, next) => prev += parseFloat(next.goods.price) * parseInt(next.num), 0))
    // 挂载完成
    onMounted(() => {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      })
      getCart({include: 'goods'}).then(res => {
        state.list = res.data
        state.result = state.list.filter(item => item.is_checked).map(item => item.id)
        state.checked = state.list.length === state.result.length
        Toast.clear()
      })
    })
    // 提交订单
    const router = useRouter()
    const onSubmit = () => {
      if (state.result.length === 0) return Toast.fail('请选则商品结算')
      router.push({name: 'CreateOrder'})
    }
    let emptyCart = require('assets/images/empty-car.png')
    return {
      ...toRefs(state), emptyCart, checkedAll, groupChange, price, onChange, deleteGood, onSubmit
    }
  }
}
</script>

<style scoped lang="scss">
.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 15px 10px 10px;
  .left {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    img {
      width: 100px;
    }
    .desc {
      text-align: left;
      .title {
        font-size: 14px;
      }
      .price {
        color: red;
        margin-top: 10px;
      }
    }
  }
  .right {
    text-align: right;
    .step {
      margin-top: 10px;
    }
  }
}
.bottom-button {
  width: 160px;
  height: 40px;
}
.submit-bar {
  margin-bottom: 50px;
}
.delete-button {
  height: 100%;
}
</style>